package com.example.springbootaop.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Arrays;

@Component
@Aspect
public class ServiceAspect {

    @Pointcut(value = "@within(com.example.springbootaop.annotation.ServiceLog)")
    public void pointCut() {

    }

    @Before("pointCut()")
    public void before(JoinPoint joinPoint) throws NoSuchMethodException {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Class<?> clazz = joinPoint.getTarget().getClass();
        Method method = clazz.getMethod(signature.getName(), signature.getParameterTypes());
        System.out.printf("[Service前置通知]: [目标类]:%s , [方法]:%s , [入参值]:%s%n"
                , clazz.getName(), method.getName(), Arrays.toString(joinPoint.getArgs()));
    }

    @AfterReturning(value = "pointCut()", returning = "result")
    public void afterReturning(JoinPoint joinPoint, Object result) {
        Class<?> clazz = joinPoint.getTarget().getClass();
        System.out.printf("[返回通知]: [目标类]:%s , [方法]:%s , [返回值]:%s%n"
                , clazz.getName(), joinPoint.getSignature().getName(), result);
    }
}
